package com.sunday.volunteer.fragment.tab;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.member.base.BaseFragment;
import com.sunday.volunteer.BaseApp;
import com.sunday.volunteer.R;
import com.sunday.volunteer.adapter.ShopAdapter;
import com.sunday.volunteer.entity.Member;
import com.sunday.volunteer.entity.Product;
import com.sunday.volunteer.http.HttpClient;
import com.sunday.volunteer.utils.BaseUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Pual's PC on 2016/10/8.
 */
public class ShopFragment extends BaseFragment {

    @Bind(R.id.title_text)
    TextView title_text;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.swipfresh_layout)
    SwipeRefreshLayout swipeRefreshLayout;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @Bind(R.id.tv_scores)
    TextView tv_scores;
    @Bind(R.id.back)
    View back;

    private int pageNo = 1;
    private boolean isCanloadMore = false;
    private LinearLayoutManager layoutManager;
    private ShopAdapter adapter;
    private List<Product> list;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_shop ,null);
        ButterKnife.bind(this , rootView);
        back.setVisibility(View.GONE);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        title_text.setText("积分商城");

        list = new ArrayList<>();
        list.add(new Product());
        adapter = new ShopAdapter(list ,R.layout.item_shop);
        adapter.setOnClickListener(onClickListener);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        swipeRefreshLayout.setColorSchemeResources(R.color.material_red, R.color.material_green,
                R.color.material_blue, R.color.material_yellow);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());
        recyclerView.setAdapter(adapter);


        handlerRecyclerView();
        getData();

    }



    private int lastVisibleItem;

    private void handlerRecyclerView() {
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                pageNo = 1;
                getData();
            }
        });
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pageNo = 1;
                getData();
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    pageNo ++;
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
                isCanloadMore = dy >0;
            }
        });
    }


    private void getData() {
        Call<ResultDO<List<Product>>> call = HttpClient.getHttpAdapter().selectScoreProduct( BaseApp.getInstance().getMemberId(),pageNo ,10 );
        call.enqueue(new Callback<ResultDO<List<Product>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Product>>> call, Response<ResultDO<List<Product>>> response) {
                if(response.body() == null || isFinish){
                    return;
                }
                if(response.body().getCode() == 0 && response.body().getResult() != null){
                    if(pageNo == 1){
                        list.clear();
                    }
                    list.addAll(response.body().getResult());
                    BaseUtil.setEmptyLayout(emptyLayout , list.size() ,null);
                    adapter.notifyDataSetChanged();
                }
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onFailure(Call<ResultDO<List<Product>>> call, Throwable t) {
                swipeRefreshLayout.setRefreshing(false);
                emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
            }
        });
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.btn:
                    Product item = (Product) v.getTag(R.id.item);
                    if(item == null){
                        return;
                    }
                    BaseUtil.openProductDetailActivity(mContext , item.getId());
                    break;
                case R.id.item:
                    item = (Product) v.getTag(R.id.item);
                    if(item == null){
                        return;
                    }
                    BaseUtil.openProductDetailActivity(mContext , item.getId());
                    break;
            }

        }
    };


    public void setData(Member member){
        tv_scores.setText(String.format("%.0f" ,member.getScore()));
    }

}
